package com.itrident.impl;

import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.template.CustomLiveTemplateBase;
import com.intellij.codeInsight.template.CustomTemplateCallback;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.patterns.StandardPatterns;
import com.itrident.loader.imlp.XmlEnumsLoader;
import com.itrident.matcher.MultipleMatcher;
import com.itrident.msg.MessageUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author cxx
 * @link com.intellij.codeInsight.template.impl.LiveTemplateCompletionContributor
 * @create 2021-04-12 15:34
 **/
public class XmlEnumLiveTemplate extends CustomLiveTemplateBase{

    public static final String TIPS = "@";

    private Project project;

    private static Pattern pattern = Pattern.compile ("^'*("+TIPS+")+(.)*IntellijIdeaRulezzz([ '])*$");

    @Nullable
    @Override
    public String computeTemplateKey(@NotNull CustomTemplateCallback callback) {
        String text = callback.getContext ().getText ();
        MessageUtil.debugNotifyMsg ("进入computeTemplateKey:"+text, MessageType.INFO);
        return text;
    }

    @Override
    public boolean isApplicable(@NotNull CustomTemplateCallback callback, int offset, boolean wrapping) {
        MessageUtil.debugNotifyMsg ("进入isApplicable:"+callback.getFileType ().getName (), MessageType.INFO);
        if (!("XML".equalsIgnoreCase (callback.getFileType ().getName ()) || "SQL".equalsIgnoreCase (callback.getFileType ().getName ()) )) {
            MessageUtil.debugNotifyMsg ("进入computeTemplateKey被返回了", MessageType.INFO);
            return false;
        }
        this.project = callback.getProject ();
        String text = callback.getContext ().getText ();
        MessageUtil.debugNotifyMsg ("获取的文本："+text, MessageType.INFO);
        boolean startsWith = text.startsWith (TIPS);
        MessageUtil.debugNotifyMsg ("isApplicable:"+(startsWith || isTextPrompt (text)), MessageType.INFO);
        return startsWith || isTextPrompt (text);
    }

    private static boolean isTextPrompt(String text){
        int i = text.indexOf (TIPS);
        if(i != -1){
            text = text.substring (i);
        }
        return pattern.matcher (text).matches ();
    }


    @Override
    public boolean supportsWrapping() {
        MessageUtil.debugNotifyMsg ("supportsWrapping", MessageType.INFO);
        return true;
    }


    @Override
    public void addCompletions(CompletionParameters parameters, CompletionResultSet result) {
//        String prefix = parameters.getOriginalPosition ().getText ();
        String prefix = result.getPrefixMatcher ().getPrefix ();
//        if(matchType == 0){
//            prefix = result.getPrefixMatcher ().getPrefix ();
//        }
        MessageUtil.debugNotifyMsg ("prefix:"+prefix, MessageType.INFO);

        //处理prefix
        String[] split = prefix.split (TIPS);
        if (prefix.endsWith (TIPS)){
            prefix = "";
        }else {
            prefix = split[split.length-1];
        }
        MessageUtil.debugNotifyMsg ("prefix post:"+prefix, MessageType.INFO);
        if(!prefix.startsWith (TIPS)){
            //作用是要覆盖我们写的@符号
            prefix =TIPS + prefix;
        }
        PrefixMatcher prefixMatcher = MultipleMatcher.create (prefix);
//        result = result.withPrefixMatcher (prefixMatcher.cloneWithPrefix (prefix));
        List<LookupElement> elements = loadElements(prefix,parameters.getPosition ().getProject ());
        MessageUtil.debugNotifyMsg ("第一轮查找:"+elements.size (), MessageType.INFO);
        List<String> eleNames = new LinkedList<> (){
            @Override
            public boolean contains(Object o) {
                return true;
//                return this.stream ().anyMatch (t->
//                    t.toLowerCase ().startsWith (o.toString ().toLowerCase ())
//                );
            }
        };
        for (LookupElement element : elements) {
            CompletionResult completionResult = CompletionResult.wrap (element, prefixMatcher,CompletionSorter.defaultSorter (parameters,prefixMatcher));
            if (completionResult != null) {
                eleNames.add (element.getLookupString ());
                result.passResult (completionResult);
                MessageUtil.debugNotifyMsg ("第二轮加入:"+completionResult.getLookupElement ().getObject (), MessageType.INFO);
            }
        }
        if (eleNames.size () > 0){
            result.restartCompletionOnPrefixChange(
                    StandardPatterns.string().oneOf(eleNames));
        }
    }

    private List<LookupElement> loadElements(String prefix, Project project) {
        XmlEnumsLoader loader = new XmlEnumsLoader (this, project);
        return loader.load (prefix);
    }

    @Override
    public void expand(@NotNull String key, @NotNull CustomTemplateCallback callback) {
    }

    @Override
    public void wrap(@NotNull String selection, @NotNull CustomTemplateCallback callback) {
    }

    @NotNull
    @Override
    public String getTitle() {
        return null;
    }

    @Override
    public char getShortcut() {
        return 0;
    }
}